#!/usr/bin/perl
#delrule.cgi

require './tgtman-lib.pl';
&ReadParse();
&error_setup($text{'error_mesg'});
$ruleline=$in{'ruleline'};
$cmd=$in{'command'};
$tgtname=$in{'tgtname'};
#&error($type);

my (@allowfile, @denyfile, $tgtline, @tgtips, @newtgtips, @newfile, @newfile_a, @newfile_d, $newtgtline, $newipstr, $newline);

if($cmd =~ /delete/){
	$ruleline =~ /(\S+):([A|D])/;
	$ip=$1;
	$type=$2;
	if($type =~ /A/){
	
  	open(AL, "/etc/initiators.allow");
  	@allowfile=<AL>;
  	close(AL);

  	foreach (@allowfile){
  		$_ =~ s/\r|\n//g;
  		if($_ =~ /^$tgtname\s+(\S+)$/){

  			$tgtline = $_;
  			@tgtips = split(/,/,$1);
  			foreach $p (@tgtips){
  				if(!($p =~ /^$ip$/)) {
  					push(@newtgtips, $p);
  				}
  			}
  			$newipstr = join(",", @newtgtips);
  			$newtgtline = $tgtname." ".$newipstr;
  			if(@newtgtips){
  				push(@newfile, $newtgtline);
  			}
  		}
  		else{
  			push(@newfile, $_);
  		}
  	}
  	
  	open(AL, ">/etc/initiators.allow");
  	foreach(@newfile) {
  		$newline = $_."\n";
  		print AL $newline;
  	}
  	close(AL);		
  		
  }
	elsif($type =~ /D/){
		
  	open(AL, "/etc/initiators.deny");
  	@allowfile=<AL>;
  	close(AL);

  	foreach (@allowfile){
  		$_ =~ s/\r|\n//g;
  		if($_ =~ /^$tgtname\s+(\S+)$/){

  			$tgtline = $_;
  			@tgtips = split(/,/,$1);
  			foreach $p (@tgtips){
  				if(!($p =~ /^$ip$/)) {
  					push(@newtgtips, $p);
  				}
  			}
  			$newipstr = join(",", @newtgtips);
  			$newtgtline = $tgtname." ".$newipstr;
  			if(@newtgtips){
  				push(@newfile, $newtgtline);
  			}
  		}
  		else{
  			push(@newfile, $_);
  		}
  	}
  	
  	open(AL, ">/etc/initiators.deny");
  	foreach(@newfile) {
  		$newline = $_."\n";
  		print AL $newline;
  	}
  	close(AL);				
		
	}
	else{
		
	}
}


if($cmd =~ /delall/){
	  #&error($tgtname);
	  #delete entry of this tgt from .allow file
 
  	open(AL, "/etc/initiators.allow");
  	@allowfile=<AL>;
  	close(AL);

  	foreach (@allowfile){
  		$_ =~ s/\r|\n//g;
  		if(!($_ =~ /^$tgtname\s+\S+$/)){
					push(@newfile_a, $_);
			}
		}  	
  	open(AL, ">/etc/initiators.allow");
  	foreach(@newfile_a) {
  		$newline = $_."\n";
  		print AL $newline;
  	}
  	close(AL);	
  	

	  #delete entry of this tgt from .deny file
  	open(AL, "/etc/initiators.deny");
  	@denyfile=<AL>;
  	close(AL);

  	foreach (@denyfile){
  		$_ =~ s/\r|\n//g;
  		if(!($_ =~ /^$tgtname\s+(\S+)$/)){
					push(@newfile_d, $_);
			}
		}  	
  	open(AL, ">/etc/initiators.deny");
  	foreach(@newfile_d) {
  		$newline = $_."\n";
  		print AL $newline;
  	}
  	close(AL);	  	
	  		  
}
system("/etc/init.d/iscsi-target restart");
#&redirect("index.cgi");
&redirect("target_iprule.cgi?tgtname=$tgtname"); 
